package com.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dao.AreaDAO;
import com.dao.KefuDAO;
import com.pojo.Area;
import com.pojo.Kefu;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 区域管理的业务层
 * @Author:ttw
 * @Date:2022-02-23
 */
@Service
public class AreaService extends ServiceImpl<AreaDAO, Area> {
    @Autowired
    private AreaDAO areaDAO;
    @Autowired
    private KefuDAO kefuDAO;

    /**
     * 分页查询
     * @param page 页数
     * @param limit 条数
     * @param areaName 区域名称
     * @return
     */
    public IPage getPage(int page,int limit,String areaName){
        Page p = new Page(page,limit);
        QueryWrapper<Area> qw = new QueryWrapper<>();
        if (StringUtil.isNotNull(areaName)){
            qw.like("areaName",areaName);
        }
        qw.orderByAsc("createTime");
        IPage iPage = areaDAO.selectPage(p,qw);
        List<Area> areas = iPage.getRecords();
        for (Area area :areas) {
            int a = kefuDAO.selectCount(new QueryWrapper<Kefu>().eq("areaId",area.getId()));
            area.setNumbers(a);
        }
        return iPage;
    }

    /**
     * 根据字段修改
     * @param id id
     * @param value 修改的值
     * @param column 修改的字段
     * @return
     */
    public int updateArea(String id,String value,String column){
        Area area = areaDAO.selectById(id);
        if (area==null){
            return 0;
        }
        if ("areaName".equals(column)){
            area.setAreaName(value);
        }else if ("areaName_en".equals(column)){
            area.setAreaName_en(value);
        }else if ("areaName_tai".equals(column)){
            area.setAreaName_tai(value);
        }else if ("areaDescribe".equals(column)){
            area.setAreaDescribe(value);
        }else if ("areaName_kh".equals(column)){
            area.setAreaName_kh(value);
        }
        return areaDAO.updateById(area);
    }

    /**
     * 查询所有区域
     * @param yuyan 语言
     * @return
     */
    public List<Area> getList(String yuyan){
        List<Area> areaList = areaDAO.selectList(new QueryWrapper<>());
        if ("en".equals(yuyan)){
            for (Area area :areaList) {
                area.setAreaName(area.getAreaName_en());
            }
        }else if ("th".equals(yuyan)){
            for (Area area :areaList) {
                area.setAreaName(area.getAreaName_tai());
            }
        }else if ("kh".equals(yuyan)){
            for (Area area :areaList) {
                area.setAreaName(area.getAreaName_kh());
            }
        }
        return areaList;
    }
}
